<?php
/**
 * 全局控制
 *
 * @copyright  Copyright (c) 2015-2025 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com/
 * @link       http://www.ncphp.com/
 * @author     NcPHP Team
 * @since      File available since Release v1.1
 */
defined('InNcPHP') or exit('Access Invalid!');

# 总控制器
class Control{
	
    public function __construct(){
        global $NC; // 全局常用参数

    }

}

# 前端控制器
class BaseHomeControl extends Control{
    protected $_must_login = false;
    # default
    public function __construct(){
        parent::__construct();
        // ---
        Tpl::setDir('home');
        Tpl::setLayout('home_layout');
        if($this->is_weixin()){
            Tpl::output('_title','玩转六盘水');
        }else{

            if($_GET['act']=='bargain' && $_GET['op'] =='index' ){
                Tpl::output('_title','友帮');
            }elseif($_GET['act']=='member' && $_GET['op'] =='index'){
                Tpl::output('_title','商城中心');
            }elseif($_GET['act']=='cate' && $_GET['op'] == 'index'){
                Tpl::output('_title','分类');
            }elseif($_GET['act']=='customize'){
                Tpl::output('_title','定制');
            }else{
                Tpl::output('_title','玩转六盘水');
            }
        }



        if($_GET['phone']==1111){
            //退出清空缓存
            session_destroy();
        }
        if(($this->_must_login && !isset($_SESSION['member'])) || (!empty($_GET['phone']) && $_GET['phone']!='1111')){
            $this->checkLogin();
        }

        if(!empty($_GET['app_lng']) && !empty($_GET['app_lat']))
        {
            $lng = $_GET['app_lng'];//经度
            $lat = $_GET['app_lat'];//纬度
            $this->position_app($lng,$lat);
        }
        //var_dump($_SESSION['member']);
       /* if(!empty($mobile) || !isset($_SESSION['member']) || !$_SESSION['member']){
            //校验登录状态
            //$this->checkLogin();
        }*/

        //定位
        //$this->position();
        //设置用户默认的住店时间
        if(!isset($_SESSION['hotel_time']) && !is_array($_SESSION['hotel_time'])){
            $this->set_hotel_time();
        }

    }


    /**
     * 用户登陆(不包含微信)
     */
    public function checkLogin() {
        if (!isset($_SESSION['member']) || !$_SESSION['member'] || !empty($_GET['phone'])) {
            $member_model = Model('member');
            if(!empty($_GET['phone']) || !empty($_POST['phone'])){
                $phone = isset($_GET['phone'])?$_GET['phone']:$_POST['phone'];
                $sign = isset($_GET['sign'])?$_GET['sign']:$_POST['sign'];
                //验证手机号是否是真实的
                if(strlen($phone)!='11'){
                    //不是真实的手机号直接跳登陆页
                    redirect('index.php?act=login&op=index');
                }
                if($this->_check_sign($phone,$sign)){
                    $member_info = $member_model->getMemberInfo(array('mobile'=>$phone));
                    if(!empty($member_info)){
                        $news_member = $this->getmeber($phone);//获取用户头像
                        if($news_member['code']=='2000' && ($member_info['headimgurl'] !=$news_member['data']['icon'] || $member_info['nickname'] !=$news_member['data']['nickname'])){
                            $member_info['headimgurl'] = $news_member['data']['icon'];
                            $member_info['nickname']  =  $news_member['data']['nickname'];
                            $member_model->updateMember(array('member_id'=>$member_info['member_id']),array('headimgurl'=>$member_info['headimgurl'],'nickname'=>$member_info['nickname']));
                        }
                        $_SESSION['member'] = $member_info;
                       if($member_info['is_merchant']==0){
                            $check = $this->check_merchant($phone);//查询此人是否是后台添加的商家
                            if($check['mc_status'] ==1){
                               //说明是商家将该用户绑定
                                if($member_model->updateMember(array('member_id'=>$member_info['member_id']),array('merchant_id'=>$check['merchant_id'],'is_merchant'=>1))){
                                    $_SESSION['member']['is_merchant'] = 1;
                                    $_SESSION['member']['merchant_id'] = $check['merchant_id'];
                                }
                            }
                        }
                    }else{
                        //新用户
                        $user_info = array();
                        $user_info['mobile'] = $phone;
                        $user_info['addtime'] = time();
                        $user_info['is_merchant'] = 0;
                        $news_member = $this->getmeber($phone);//获取用户头像
                        $check = $this->check_merchant($phone);//查询此人是否是后台添加的商家
                        if($check['mc_status']==1){
                            $user_info['is_merchant']=1;
                            $user_info['merchant_id']= $check['merchant_id'];
                        }
                        if($news_member['code']=='2000'){
                            $user_info['headimgurl'] = $news_member['data']['icon'];
                            $user_info['nickname'] = $news_member['data']['nickname'];
                        }
                        $member_id = $member_model->addMember($user_info);
                        if($member_id>0){
                            $_SESSION['member'] = $user_info;
                            $_SESSION['member']['member_id'] = $member_id;
                        }
                    }
                }else{
                    exit;
                }
            }else{
                redirect('index.php?act=login&op=index');
            }
        }else{
            redirect('index.php?act=login&op=index');
        }
    }

    /**
     * 微信用户登录
     */
    public function checkLogin1() {
        if (!isset($_SESSION['member']) || !$_SESSION['member'] || !empty($_GET['phone'])) {
            $member_model = Model('member');
            if(!$this->is_weixin()){
                if(!empty($_GET['phone']) || !empty($_POST['phone'])){

                    $phone = isset($_GET['phone'])?$_GET['phone']:$_POST['phone'];
                    $sign = isset($_GET['sign'])?$_GET['sign']:$_POST['sign'];
                    if($this->_check_sign($phone,$sign)){
                        $member_info = $member_model->getMemberInfo(array('mobile'=>$phone));
                        if(!empty($member_info)){
                            $news_member = $this->getmeber($phone);//获取用户头像
                            if($news_member['code']=='2000'){
                                $member_info['headimgurl'] = $news_member['data']['info']['member_icon'];
                                $member_model->updateMember(array('member_id'=>$member_info['member_id']),array('headimgurl'=>$member_info['headimgurl']));
                            }
                            $_SESSION['member'] = $member_info;
                        }else{
                            //新用户
                            $user_info = array();
                            $user_info['mobile'] = $phone;
                            $user_info['addtime'] = time();
                            $user_info['is_merchant'] = 0;
                            $news_member = $this->getmeber($phone);//获取用户头像
                            if($news_member['code']=='2000'){
                                $user_info['headimgurl'] = $news_member['data']['info']['member_icon'];
                            }
                            $member_id = $member_model->addMember($user_info);
                            if($member_id>0){
                                $_SESSION['member'] = $user_info;
                                $_SESSION['member']['member_id'] = $member_id;
                            }
                        }
                    }else{
                        exit;
                    }

                }else{
                    redirect('index.php?act=login&op=index');
                }


            }else{
                require_once(BASE_DATA_PATH.'/vendors/wechat/wesdk.php');
                $wesdk = new wesdk();
                $code = isset($_GET['code']) ? $_GET['code'] : false;
                if ($code) {
                    $userInfo = $wesdk->OAuthUserInfo($code);
                    if ($userInfo) {
                        /* @var memberModel $member_model */
                        $member = $member_model->getMemberInfo(array('unionid'=>$userInfo['unionid']));

                        if ($member) {
                              $_SESSION['member'] = $member;
                        } else {
                            $u = $wesdk->getUserInfo($userInfo['openid']);

                            if (isset($u['subscribe'])) {
                                $userInfo['subscribe'] = $u['subscribe'];
                            } else {

                                exit('未获取到用户关注信息');
                            }
                            $member_s = $member_model->getMemberInfo(array('openid'=>$userInfo['openid']));//根据open_id 查询该用户是否存在
                            if($member_s){
                                //修改
                                $updata_userInfo = array();
                                $updata_userInfo['is_merchant'] = 0;
                                $updata_userInfo['unionid'] = $u['unionid'];
                                $updata_userInfo['belong_proxy']=null;
                                $updata_userInfo['subscribe']= $u['subscribe'];
                                if($member_model->updateMember(array('openid'=>$userInfo['openid']),$updata_userInfo)){
                                    $userInfo['member_id'] =$member_s['member_id'];
                                    $_SESSION['member'] = $member_s;
                                }else{
                                    exit('数据库更新用户失败');
                                }
                            }else{
                                //新增
                                unset($userInfo['privilege']);
                                unset($userInfo['language']);
                                $userInfo['is_merchant'] = 0;
                                $userInfo['belong_proxy'] = null;
                                $userInfo['unionid'] = $u['unionid'];
                                $userInfo['addtime'] = time();
                                $member_id = $member_model->addMember($userInfo);
                                if ($member_id) {
                                    $userInfo['member_id'] = $member_id;
                                    $_SESSION['member'] = $userInfo;
                                } else {
                                    exit('数据库添加用户失败');
                                }
                            }

                        }
                    } else {
                        exit('授权错误');
                    }
                } else {
                    $wesdk->OAuth(true);
                }
            }
            }else{
            redirect('index.php?act=login&op=index');
        }

    }

    /**
     * 定位
     */
    public function position() {
        if (!isset($_SESSION['pos']) || !$_SESSION['pos']) {
            /** @var areaModel $area */
            $area = Model('area');

            $key = '5c7baac99d10897f7b2afa1aec0622e3';
            $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
            $api = 'http://restapi.amap.com/v3/ip?key='.$key.'&ip='.$ip;
            $ret = json_decode(file_get_contents($api), true);

            $city_name = empty($ret['city']) ? '六盘水' : rtrim($ret['city'],'市');

            $city_name = mb_substr($city_name, 0, 3, 'UTF-8');
            $condition = array();
            $condition['name'] = array('like', $city_name . '%');
            $condition['type'] = 2;
            $city = $area->getAreaInfo($condition);
            if (!$city) {
                $condition['name'] = '六盘水';
                $city = $area->getAreaInfo($condition);
            }
            $_SESSION['pos'] = array('city_id'=>$city['area_id'], 'city_name'=>$city['name']);
        }
    }

    /**
     * 根据APP端传值定位
     *
     * @param $lng  经度
     * @param $lat  纬度
     */
     protected function position_app($lng,$lat)
     {
         /** @var areaModel $area */
         $area = Model('area');
         $location = array(
             'lat' => $lat,
             'lng' => $lng
         );
         $url = 'http://restapi.amap.com/v3/geocode/regeo?key=5c7baac99d10897f7b2afa1aec0622e3&location='.$location['lng'].','.$location['lat'];
         $geocode = json_decode($this->httpGet($url));
         $cityName = $geocode->regeocode->addressComponent->city;
         $cityName = mb_substr(rtrim($cityName, '市'),0,3,'UTF-8');
         $condition = array();
         $condition['name'] = array('like', $cityName . '%');
         $condition['type'] = 2;
         $cityInfo = $area->getAreaInfo($condition);
         if ($cityInfo && $cityInfo['area_id']) {
             $_SESSION['pos'] = array('city_id'=>$cityInfo['area_id'], 'city_name'=>$cityInfo['name']);
         }
         $_SESSION['pos']['js'] = true;
         $_SESSION['location']  = array('lat'=>$location['lng'],'lng'=>$location['lat']);
     }

    # SEO 设置
    public function _seo($seo = array()){
        list($title,$keywords,$description) = $seo;
        $seo = array();
        $seo['title'] = $title;
        $seo['keywords'] = $keywords;
        $seo['description'] = $description;
        Tpl::output('seo',$seo);
    }

    /**
     * 错误请求
     * @param $message
     */
    public function error($_title,$message){
        if(empty($_title)){
            Tpl::output('_title','错误-提示');
        }else{
            Tpl::output('_title',$_title);
        }
        Tpl::output('message',$message);
        Tpl::showpage('error');
    }


    //判断是否在微信里面访问
   public  function is_weixin() {
        if (stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        } return false;
    }

    /**
     * 验证签名
     * @mobile  手机号
     * @sian 签名
     */
    private function _check_sign($moblie,$sian)
    {
        $_sign = md5($moblie.API_KEY);
        if($_sign==$sian){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取当前的时间戳及第二天的时间
     */
    public function set_hotel_time()
    {
        $_SESSION['hotel_time'] = array(
            'startdate'=>date('Y-m-d'),//入驻时间
            'enddate' => date("Y-m-d",strtotime("+1 day")),//离店时间
            'numdate'=>1 //入住的总天数
        );
    }

    /**
     * 修改酒店预定时间
     */
    public function edit_check_time()
    {
        $startdate = $_POST['startdate'];//入驻时间
        $enddate   = $_POST['enddate'];//离店时间
        $numdate   = intval($_POST['numdate']);
        if($startdate && $enddate && $numdate){
            $_SESSION['hotel_time'] = array(
                'startdate'=>$startdate,//入驻时间
                'enddate' => $enddate,//离店时间
                'numdate'=>$numdate //入住的总天数
            );
            exit(json_encode(array('res'=>true)));
        }
        exit(json_encode(array('res'=>false)));
    }



    /**
     * 申请退款释放库存
     */
   public function restore_store($order_id){
       /* @var orderModel $order_model */
       $order_model = Model('order');
       /* @var order_ticketModel $order_ticket_model */
       $order_ticket_model = Model('order_ticket');
        if($order_id>0){
            $order = $order_model->getOrderInfo(array('order_id'=>$order_id));
            if($order['order_status']==20 && $order && $order['order_type']==2){
                //门票
                //还原门票库存
                Model::beginTransaction();
                try {
                    $order_tickets = $order_ticket_model->getOrderTicketList(array('order_id'=>$order['order_id']));

                    //还原库存
                    if ($order['is_set_time']==0) {
                        /** @var ticket_skuModel $sku_model */
                        $sku_model = Model('ticket_sku');
                        foreach ($order_tickets as $ticket) {
                            $condition = array('tk_id'=>$order['ticket_id'],'type_id'=>$ticket['type_id'],'spec_id'=>$order['spec_id']);
                            $sku_model->where($condition)->setInc('sku_store', $ticket['ot_num']);
                        }
                        Model::commit();
                    } else {
                        /** @var ticket_dateModel $date_model */
                        $date_model = Model('ticket_date');
                        /** @var ticket_sku_dateModel $sku_model */
                        $sku_model = Model('ticket_sku_date');
                        $date = $date_model->getTicketDateInfo(array('tk_id'=>$order['ticket_id'],'date'=>$order['allow_date']));
                        foreach ($order_tickets as $ticket) {
                            $condition = array('date_id'=>$date['date_id'],'type_id'=>$ticket['type_id'],'spec_id'=>$order['spec_id']);
                            $sku_model->where($condition)->setInc('sku_store', $ticket['ot_num']);
                        }
                        Model::commit();
                    }
                    //$res = $order_model->updateOrder(array('order_id'=>$order['order_id']), array('order_status'=>30));

                } catch (\Exception $e) {
                    Model::rollback();
                    return false;
                }
            }elseif($order['order_status']==20 && $order['order_type']==1 && $order){
                $order_hotel_model = Model('order_hotel');
                //还原酒店房间
                Model::beginTransaction();
                try{
                    $_res=$order_hotel_model->updateOrderHotel(array('order_id'=>$order['order_id']),array('status'=>2));
                    if($_res){
                        Model::commit();
                        $ret = array('errcode'=>0,'errmsg'=>'');
                    }else{
                        Model::rollback();
                        return false;
                    }
                }catch (\Exception $e) {
                    Model::rollback();
                    return false;
                }
            }elseif($order['order_status']==20 &&  $order){
                //还原美食库存或者旅行社库存
                $order_goods = Model('order_goods');
                $good_info = $order_goods->getOrderGoodsInfo(array('order_id'=>$order['order_id']),'og_num,goods_id');
                if($order['order_type']==3){
                    //释放美食库存
                    $food_model = Model('food');
                    $food_model->addFoodStock($good_info['goods_id'],$good_info['og_num']);
                }elseif($order['order_type']==4){
                    $itinerary_model = Model('itinerary');
                    $itinerary_model->addItineraryStock($good_info['goods_id'],$good_info['og_num']);
                }
            }
        }

    }

    /**
     * 修改酒店超时未付款的订单状态
     */
    public  function update_order_status()
    {
        $condition = array();
        $past_time = time()-intval(30)*60;
        $condition['order_status'] =10;
        $condition['order_type']   = HOTEL_MARK;
        $condition['add_time'] = array('elt',$past_time);
        /* @var orderModel $order_model */
        $order_model = Model('order');
        /* @var order_hotelModel $order_hotel_model */
        $order_hotel_model = Model('order_hotel');
        $order_list = $order_model->getOrderList($condition,'order_id');
        if(!empty($order_list)){
            //将超时未支付订单状态改为取消状态
            $ids = array();
            foreach($order_list as $ke=>$vo){
                $ids[] = $vo['order_id'];
            }
            $ids = implode(',',$ids);
            $order_model->updateOrder(array('order_id'=>array('in',$ids)),array('order_status'=>30));
            $order_hotel_model->updateOrderHotel(array('order_id'=>array('in',$ids)),array('status'=>2));
            unset($ids,$order_list);
        }
    }

    /**
     * 查询该手机号是否是商家
     */
    public function check_merchant($mobile)
    {
        /** @var member_merchantModel $merchant_model */
        $merchant_model = Model('member_merchant');
        $merchant_info = $merchant_model->getMerchantInfo(array('mc_phone'=>$mobile));
        if($merchant_info && is_array($merchant_info)){
            return $merchant_info;
        }else{
            return false;
        }
    }


    //获取新闻系统用户信息

    public  function getmeber($mobile)

    {
        $url = "https://coolps.com.cn/api/mobile_info?mobile=".$mobile;
        //$url = "http://lps.app.todayguizhou.com:100/appAPI/index.php?act=community&op=get_member_info";
        $info = $this->httpGet($url);
        return json_decode($info,true);
    }

    public function httpPost($url, $data, $options = array())
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, $options + array(
                CURLOPT_POST => true,
                CURLOPT_HEADER => false,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_SSL_VERIFYPEER => false,
            ));
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * HTTP/HTTPS请求
     * @param string $url 请求的URL
     * @param array $options CURL选项
     * @return mixed 成功返回获取到的数据,失败返回false
     */
    public function httpGet($url, $options = array())
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, $options + array(
                CURLOPT_HEADER => false,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
            ));
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}

?>
